package com.langyiquan.front.consumer;

import com.langyiquan.enums.OrderStatus;
import com.langyiquan.mapper.ItemSpecMapper;
import com.langyiquan.mapper.ItemsMapper;
import com.langyiquan.mapper.OrdersMapper;
import com.langyiquan.pojo.ItemSpec;
import com.langyiquan.pojo.Items;
import com.langyiquan.pojo.OrderItems;
import com.langyiquan.pojo.Orders;
import com.langyiquan.service.OrderService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
public class Consumer {

    private static final Logger logger = LoggerFactory.getLogger(Consumer.class);

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ItemSpecMapper itemSpecMapper;

    @RabbitListener(queues = "dxl_queue_name")
    public void handler(Message message, Channel channel) throws IOException {

        byte[] body = message.getBody();
        String orderId = new String(body, StandardCharsets.UTF_8);
        logger.info("消费者接收到订单：" + orderId);
        Orders orders = ordersMapper.selectByPrimaryKey(orderId);
        logger.info("订单状态： " + orders.getOrderStatus());
        if (OrderStatus.WAIT_PAY.type.equals(orders.getOrderStatus())) {
            orderService.updateOrderStatus(orderId, OrderStatus.CLOSE.type);

            List<OrderItems> orderItemLists= orderService.queryPendingComment(orderId);
            for(OrderItems oi: orderItemLists){
                Integer buyCounts = oi.getBuyCounts();
                ItemSpec itemSpec = new ItemSpec();
                itemSpec.setId(oi.getItemSpecId());
                ItemSpec updateItemSpec = itemSpecMapper.selectByPrimaryKey(itemSpec);
                updateItemSpec.setStock(updateItemSpec.getStock()+buyCounts);
                itemSpecMapper.updateByPrimaryKeySelective(updateItemSpec);
            }

        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

}
